package no.gnet.edvd.web.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import no.gnet.edvd.DataStore;
import no.gnet.edvd.lightweight.CompactComment;
import no.gnet.edvd.types.Comment;
import no.gnet.edvd.web.cache.MemCache;
import no.gnet.edvd.web.types.EdvdSessionUser;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CommentController extends CommonController {

	private static Logger logger = Logger.getLogger(CommentController.class);
	private static final String COMMENTS_CACHEKEY_PREFIX = "comments_";

	@Autowired
	DataStore datastore;

	HashMap<String, Object> cache = new HashMap<String, Object>();

	@RequestMapping(value = "/api/events/comment", method = RequestMethod.POST)
	public @ResponseBody
	String postComment(HttpServletRequest request,@RequestBody CompactComment comment) {
		logger.debug("Inside postComment, comment is " + comment);
		EdvdSessionUser sessionUser = sessionUser(request);
		if (sessionUser != null) {
			datastore.addComment(sessionUser.getPlayer(), comment.getEventid(), comment.getComment());
			MemCache.markDirty(COMMENTS_CACHEKEY_PREFIX + comment.getEventid());
			return "ok";
		}
		return "nok";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/api/comments/{eventid}", method = RequestMethod.GET)
	public @ResponseBody
	List<Comment> loadCommentsForEvent(@PathVariable String eventid) {
		logger.info("Getting comments for event " + eventid );
		int iid = Integer.parseInt(eventid);
		List<Comment> comments = (List<Comment>) MemCache
				.get(COMMENTS_CACHEKEY_PREFIX + eventid);
		if (comments == null) {
			comments = datastore.loadCommentsForEvent(iid);
			MemCache.put(COMMENTS_CACHEKEY_PREFIX + eventid, comments);
		}
		
		for (Iterator<Comment> iterator = comments.iterator(); iterator.hasNext();) {
			logger.info("comment: "+ iterator.next());
		}
		
		return comments;
	}

}
